<!-- 主页面 -->
<template>
  <div class="main">
      <div v-if="firstPage" style="height:100%;overflow:hidden;">
        <load-more style="margin-top:50%;" :show-loading="false" tip="暂无数据" background-color="#fbf9fe"></load-more>
      </div>
    <div v-else>
      <div class="target" v-if="status">
        <group title="特征(连续型数值默认填入平均值)" style="overflow:hidden;">
          <cell-box style="padding: 0;" v-for="item in templateContext.feature" :key="item.fields">
            <x-number :title="item.name+'('+item.min+'-'+item.max+')'" v-if="item.type==='INPUTNUMBER'" :min="item.min" :max="item.max"
              fillable :value="1" :step="0.5" v-model="item.value"></x-number>
            <popup-picker :title="item.name" v-if="item.type==='SELECT'" show-name :columns="1" :data="item.options"
              v-model="item.value" placeholder="请选择"></popup-picker>
          </cell-box>
        </group>
        <box gap="10px 10px">
          <x-button :gradients="['#A644FF', '#FC5BC4']" :disabled="loading" :show-loading="loading" @click.native="Forecastbtn">预测(Forecast)</x-button>
        </box>
        <toast v-model="show" type="warn" :time="1500">请选择完整特征后再预测</toast>
      </div>
      <div class="result" v-else>
        <form-preview :header-label="this.templateContext.target[0].name" :body-items="probas" :footer-buttons="buttons"></form-preview>
      </div>
    </div>
  </div>
</template>
<script>
  import {
    forcast
  } from '@/service/home';
  import {
    Group,
    CellBox,
    PopupPicker,
    XNumber,
    XButton,
    Box,
    Toast,
    FormPreview,
    LoadMore 
  } from 'vux'
  export default {
    components: {
      Group,
      PopupPicker,
      XNumber,
      CellBox,
      XButton,
      Box,
      Toast,
      FormPreview,
      LoadMore 
    },
    data() {
      return {
        loading: false,
        show: false,
        status: true,
        firstPage: true,
        Accesskey: '',
        modelId: '',
        serviceId: '',
        endpointId: '',
        modelTempList: [],
        templateContext: {},
        probas: [],
        buttons: [{
          style: 'primary',
          text: '返回预测',
          onButtonClick: (name) => {
            this.status = true;
          }
        }]
      }
    },
    computed: {},
    created() {
        // 通过postMessage给iframe传递数据（这里是接收数据）
      window.addEventListener('message', (event) => {
        var origin = event.origin || event.originalEvent.origin;
        if (origin !== 'http://localhost:9090') return;
        this.firstPage = false;
        this.getContext(event.data);
      }, false);
    },
    mounted() {},
    methods: {
      async Forecastbtn() {
        // 点击预测按钮函数
        // 1.检测所有的下拉选框是否都已经选择
        let features = this.templateContext.feature;
        let status = features.every(item => {
          if (item.type === 'SELECT') {
            return item.value.length > 0
          } else {
            return true;
          }
        });
        if (!status) {
          this.show = true;
          return;
        }
        this.status = false;
        // 2.发送请求
        let res = await forcast({
          accessKey: this.Accesskey,
          modelId: this.modelId,
          serviceId: this.serviceId,
          endpointId: this.endpointId,
          data: {
            features: this.resolveData()
          }
        });
        if (res) {
          let {
            result
          } = res.data;
          if (result.probas) {
            this.resolveForcastData(result.probas);
          }
        }
      },
      resolveForcastData(probas) {
        //   处理预测请求返回数据的结果
        let target = this.templateContext.target;
        let options = target[0].options;
        let temp = [];
        options.forEach(item => {
          temp.push({
            label: item.name,
            value: (probas[item.value + ''] * 100).toFixed(2) + '%'
          });
        });
        this.probas = temp;
      },
      resolveData() {
        //   处理用户输入或者填写的数值
        let features = this.templateContext.feature;
        let temp = {};
        features.forEach(item => {
          if (item.type === 'SELECT') {
            temp[item.fields] = item.value[0];
          } else {
            temp[item.fields] = item.value;
          }
        });
        return temp;
      },
      getContext(res) {
        //   处理通过postMessage接收的数据
        this.modelId = res.modelId;
        this.serviceId = res.serviceId;
        this.endpointId = res.endpointId;
        this.Accesskey = res.Accesskey;
        let feature = res.feature;
        feature.forEach(item => {
          if (item.type === 'INPUTNUMBER') {
            item.value = item.average;
          } else if (item.type === 'SELECT') {
            item.value = [];
          }
        })
        this.templateContext = res;
      }
    }
  }

</script>
<style lang='scss' scoped>
  .main {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    .target {
      width: 100%;
      .weui-cell {
        box-sizing: border-box;
        width: 100%;
      }
      .vux-cell-box {
        width: 100%;
      }
    }
    .result {
      width: 100%;
    }
  }

</style>
